<template>
  <div>
    <el-dialog v-model="openFlag" title="耗材入库单" width="75%" append-to-body>

      <el-scrollbar max-height="65vh">
        <div class="ui_el_dialog_body">
          <el-form :model="formData" :rules="rules" label-width="80">
            <el-row>
              <el-text class="from-title-style">基本信息</el-text>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="仓库" prop="warehouseId">
                  <warehouse-select v-model="formData.warehouseId"></warehouse-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="入库时间" prop="warehouseTime">
                  <date-editor v-model="formData.warehouseTime" placeholder="入库时间" >
                  </date-editor>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="供应商" prop="supplier">
                  <el-input v-model="formData.supplier" placeholder="请输入供应商" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input type="textarea" v-model="applyData.remark" placeholder="请输入" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-text class="from-title-style">耗材列表</el-text>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                  class="resources"
                  @click="handleChoose"
              >添加耗材</el-button>
            </el-col>
          </el-row>
          <vxe-table v-loading="tableData.loading" :data="tableData.list">

            <vxe-column width="120" title="图片" align="center" field="number">
              <template #default="scope">
                <el-tooltip v-if="scope.row.imgUrl"
                            class="box-item"
                            effect="dark"
                            placement="right-start"
                >
                  <template #content>
                    <img alt="" :src="showImg(scope.row.imgUrl)" width="100" height="100" />
                  </template>
                  <img alt="" :src="showImg(scope.row.imgUrl)" width="30" height="30" />
                </el-tooltip>
                <span v-else>没有图片</span>
              </template>
            </vxe-column>
            <vxe-column width="120" title="编码" align="center" field="number"/>
            <vxe-column width="180" title="名称" align="center" field="name"/>
            <vxe-column width="180" title="单价" align="center" field="name">
              <template #default="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </vxe-column>
            <vxe-column width="180" title="数量" align="center" field="num">
              <template #default="scope">
                <el-input v-model="scope.row.num"></el-input>
              </template>
            </vxe-column>
            <vxe-column width="180" title="总金额" align="center" field="totalPrice">
              <template #default="scope">
                {{getTotalPrice(scope.row)}}
              </template>
            </vxe-column>
            <vxe-column width="120" title="分类" align="center" field="categoryName"/>
            <vxe-column width="120" title="商品条码" align="center" field="barcode"/>
            <vxe-column width="120" title="品牌" align="center" field="brand"/>
            <vxe-column width="120" title="规格型号" align="center" field="model"/>
            <vxe-column width="120" label="操作" align="center" fixed="right">
              <template #default="{ row, index }">
                <el-button
                    link
                    type="primary"
                    @click="handleDelete(row, index)"
                >删除</el-button>

              </template>
            </vxe-column>

          </vxe-table>
        </div>
      </el-scrollbar>


      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="sub">提交</el-button>
          <el-button @click="close">取 消</el-button>
        </el-row>

      </div>
    </el-dialog>

    <choose-file-dialog ref="chooseDialog" @sub="onChooseSub"></choose-file-dialog>

  </div>
</template>

<script setup>

import api from "@/api/consume/inApply.js";
import WarehouseSelect from "./WarehouseSelect";
import ChooseFileDialog from "./ChooseFileDialog.vue";
import DateEditor from "@/components/Common/DateEditor.vue";

const { proxy } = getCurrentInstance();
const emit = defineEmits(['sub']);

const chooseDialog = ref();

const openFlag = ref(false);
const tableData = reactive({
  loading: false,
  list: []
});

const applyDataInit = {
  id: null,
  applyType: 'HCRK',
  remark: null
}

const applyData = reactive({...applyDataInit});

// 是否编辑
const isEdit = ref(false);

const rules = reactive({
  warehouseId: [{ required: true, message: "不能为空", trigger: "blur" }]
});

const applyType = 'HCRK';

const formDataInit = {
  applyType: applyType,
  warehouseId: null,
}

let actionType = '';
let deletedItem = [];

const formData = reactive({...formDataInit});

function getTotalPrice(row) {
  if (!row.price || !row.num) {
    return 0;
  }
  return row.price * row.num;
}

function reset() {
  Object.assign(formData, formDataInit);
  tableData.list = [];
  deletedItem = [];
}

function open(row) {

  openFlag.value = true;
  reset();

  if (row) {
    isEdit.value = true;
    const id = row.id;
    api.detail(id).then(response=> {
      Object.assign(applyData, response);

      let resFormData = response.formData;
      if (resFormData) {
        if (typeof resFormData === 'string') {
          resFormData = JSON.parse(resFormData);
        }
        Object.assign(formData, resFormData);
      }
      let relItems = formData.items;
      if (!relItems) {
        relItems = []
      }
      tableData.list = relItems;
    });
  } else {
    isEdit.value = false;
  }
}

function close() {
  openFlag.value = false;
}

function showImg(img) {
  return import.meta.env.VITE_APP_BASE_API + img;
}

function handleChoose() {
  chooseDialog.value.open();
}
function handleDelete(row, index) {
  // 如果是编辑状态需要把删除的行存起来
  if (actionType === 'edit') {
    deletedItem.push(row);
  }
  tableData.list.splice(index, 1);

}

function getParams() {
  const apply = { ...applyData };
  formData.items = tableData.list;
  apply.formData = JSON.stringify(formData);
  return {
    edit: isEdit.value,
    apply: apply
  }
}

/** 提交按钮 */
function save() {

  api.save(getParams()).then(() => {
    emit("sub");
    close();
  });
}

function sub() {
  api.saveAndSub(getParams()).then(() => {
    emit("sub");
    close();
  });
}

function onChooseSub(selected) {
  if (selected) {
    selected.forEach((item)=> {
      let row = {...item};
      row.fileId = row.id;
      delete row.id;
      row.num = 1;
      tableData.list.push(row);
    })
  }
}

defineExpose({
  open
})


</script>
